﻿using System;
using System.IO;
using System.Linq.Expressions;
using MongoDAO.Providers;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;

namespace MongoDAO
{
    public class GridFS
    {
        private readonly MongoGridFS _mongoGridFS;

        public GridFS() : this(new MongoDatabaseProvider().GetDatabase())
        {
        }

        public GridFS(MongoDatabase database)
        {
            _mongoGridFS = database.GetGridFS(new MongoGridFSSettings());
        }

        public MongoGridFSFileInfo ImportFile(Stream stream, string fileName, GridFSImportOptions importOptions)
        {
            if (stream == null) throw new ArgumentNullException("stream");
            if (fileName == null) throw new ArgumentNullException("fileName");
            if (importOptions == null) throw new ArgumentNullException("importOptions");

            var mongoGridFSCreateOptions = new MongoGridFSCreateOptions()
                {
                    Id = BsonValue.Create(importOptions.IdGenerator.GenerateId(null, null)),
                    ContentType = importOptions.ContentType,
                    UploadDate = DateTime.Now
                };

            return _mongoGridFS.Upload(stream, fileName, mongoGridFSCreateOptions);
        }

        public MongoGridFSFileInfo FindOneById(BsonValue id)
        {
            return _mongoGridFS.FindOneById(id);
        }

        [Obsolete("Not Tested")]
        public void Delete(Expression<Func<MongoGridFSFileInfo, bool>> expression)
        {
            _mongoGridFS.Delete(Query<MongoGridFSFileInfo>.Where(expression));
        }

        public void DeleteById(BsonValue id)
        {
            _mongoGridFS.DeleteById(id);
        }
    }

    public class GridFSImportOptions
    {
        public IIdGenerator IdGenerator { get; set; }
        public string ContentType { get; set; }
    }


}
